package com.uu.visitor;

import org.commonmark.node.*;

import java.security.MessageDigest;
import java.util.Objects;

public class ToolVisitor extends AbstractVisitor {
    Node node = null;

    public ToolVisitor(Node node) {
        this.node = node;
    }

    @Override
    public void visit(Text text) {
        String literal = text.getLiteral();
        if (Objects.nonNull(literal)) {
            String md5Hash = generateMd5(literal);
            text.setLiteral(md5Hash);
        }
        super.visit(text);
    }

    @Override
    public void visit(Heading heading) {
        //if (List.of(1, 2).contains(heading.getLevel())) { // 一级标题 ...
        Text titleText = (Text) heading.getFirstChild();
        if (titleText != null) {
            String originalText = titleText.getLiteral();
            String md5Hash = generateMd5(originalText);
            titleText.setLiteral(md5Hash);
        }
        //}
        // 继续遍历子节点
        visitChildren(heading);
    }

    @Override
    public void visit(Image image) {
        String destination = image.getDestination();
        System.out.println(destination);
        image.setDestination("http://fffgg");
        super.visit(image);
    }

    private String generateMd5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hash = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5生成失败", e);
        }
    }
}
